-- Copyright 2012 Martti Merilaid, Nicolas BARBOTIN
-- This file is part of LuaTanks.
-- 
-- LuaTanks is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 
-- LuaTanks is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
-- 
-- You should have received a copy of the GNU General Public License
-- along with LuaTanks.  If not, see <http://www.gnu.org/licenses/>.

LTanks = LTanks or {}
LTanks.Contests = {}

-- \func LTanks.CanCreateContest
-- \desc Checks if a player is able to create a contest (to be overrided with admin addons)
-- \param ply Player The player
-- \return Boolean true if the player can, false if he can't
function LTanks.CanCreateContest(ply)
	return (ply and ply:IsValid())
end

-- \func LTanks.CreateContest
-- \desc Create a contest
-- \param starter Player The man who started the contest
-- \param members Table the list of members
-- \param maxTime Integer The time limit for coding
-- \return Integer The contest's ID (between 0 and 15 inclusive) or a negative value if there was an error
function LTanks.CreateContest(starter, members, maxTime)
	local cID = table.Count(LTanks.Contests) - 1
	if cID >= 15 then return -1 end -- Too much contest !!
	if maxTime < 5 or maxTime > 1440 then return -2 end -- Invalid time !!
	if cID < 0 then cID = 0 end -- First Contest

	LTanks.Contests[cID] = {}
	LTanks.Contests[cID].owner = starter
	LTanks.Contests[cID].members = members
	LTanks.Contests[cID].phase = LTanks.PHASE_WAITING
	LTanks.Contests[cID].maxTime = maxTime

	-- Let's send the message to all members
	local sendTo = table.Copy(members)
	table.insert(sendTo, starter)

	net.Start("LuaTanks")
	net.WriteInt(LTanks.MSG_START, 8)
	net.WriteInt(cID, 4)
	net.WriteEntity(starter)
	-- net.WriteInt(maxTime, 16)
	net.Send(sendTo)

	return cID
end

net.Receive("LuaTanks", function(len, playr)
	local msgId = net.ReadInt(8)

	if msgId == LTanks.MSG_CANCEL_CONTEST then
		local cID = net.ReadInt(4)
		if cID < 0 or cID > 15 or !LTanks.Contests[cID] then print("Sorry") return end -- Invalid Contest
		if LTanks.Contests[cID].owner:SteamID() != playr:SteamID() then print("U do not own this cont3st") return end -- Not the owner

		net.Start("LuaTanks")
		net.WriteInt(LTanks.MSG_CANCEL_CONTEST, 8)
		net.Send(LTanks.Contests[cID].members)
	else
		-- Unknown net message ID
		MsgN("[LuaTanks] Unknown net message ID " .. tostring(msgId) .. " !")
	end
end)